#!/usr/bin/ruby
$: << File.join(File.expand_path(File.dirname(__FILE__)), "..")

require 'rubygems'
require 'optparse'
require 'EasyHadoop'

#
#@author: Ritesh Agrawal
#description: uses reservoir sampling technique
#

class Sample < EasyHadoop
	
	attr_reader :hold, :line_count
	#constructor
	def initialize(arguments)
		super(arguments)
		@hold = []
		@line_count = 0
		
	end
	
	def set_mandatory
		super
		@mandatory << :size
	end

	def set_commands
		super
		@optparse.banner = "Usage: ruby #{File.basename(__FILE__)} [OPTIONS]"
		
		@options[:size]=nil
		@optparse.on('-s','--size NUM', Integer,"Number of sample records") do |value|
			@options[:size] = value
		end
	end
	
	def print
		@hold.each{|line| yield line}
	end

	def execute(line)
		
		return if line.nil? or line.strip.chomp.empty?
				
		@line_count = @line_count + 1
		
		line = line.strip.chomp
		if @hold.length < @options[:size]
			hold << line
		else
			j = rand(@line_count)
			@hold[j] = line if (j < @options[:size])
		end
		
	end

end

# Scripting Option
if __FILE__ == $0
    cls = Sample.new(ARGV)
    STDIN.each_line{|line|
	  cls.execute(line)
    }
    cls.print{|line|
    	puts line	
    }
    
end